#pragma once
#include <functional>
#include <sys/epoll.h>
#include "sock.hpp"
#include "err.hpp"

namespace epoll_ns
{
    static const int defaultport = 8081;
    static const int defaultfd = -1;
    static const int defaultnum = 64;
    static const int size = 128;

    using func_t = std::function<std::string(const std::string &)>;
    class EpollServer
    {
    private:
        int _port;
        int _listensock;
        int _epollfd;                 // epoll模型fd
        struct epoll_event *_revents; // 读事件就绪的数组指针
        int _num;                     // 从就绪队列拿出来的fd数量
        func_t _func;

    public:
        EpollServer(func_t func, uint16_t port = defaultport, int num = defaultnum)
            : _port(port),
              _listensock(-1),
              _epollfd(defaultfd),
              _revents(nullptr),
              _num(num),
              _func(func)
        {
        }
        void initServer()
        {
            // 1.创建listensock
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);
            // 2.创建epoll模型
            _epollfd = epoll_create(size);
            if (_epollfd < 0)
            {
                logMessage(ERROR, "epoll create err: %s", strerror(errno));
                exit(EPOLL_CREATE_ERR);
            }
            // 3.将listensock添加到epoll模型
            struct epoll_event ev;
            ev.data.fd = _listensock;
            // 关心读事件    EPOLLIN | EPOLLET 边缘触发 fd要设置非阻塞
            // ET模式下只通知一次，需要循环读，读到读完为止；如果是阻塞fd，读到读完时会阻塞
            ev.events = EPOLLIN;
            // ev.events = EPOLLIN | EPOLLET;
            epoll_ctl(_epollfd, EPOLL_CTL_ADD, _listensock, &ev); // 添加到红黑树中
            // 4.申请就绪事件数组空间
            _revents = new struct epoll_event[_num];
        }

        void start()
        {
            // 单位是ms
            int time = 2000; // 0立即返回 >0等time时间返回 -1阻塞等待
            while (1)
            {
                int n = epoll_wait(_epollfd, _revents, _num, time); // 一次最多取_num个
                switch (n)
                {
                case 0: // 超时返回
                    logMessage(NORMAL, "timeOut...");
                    break;
                case -1: // 失败
                    logMessage(WARNING, "poll error, code: %d, err string:%s", errno, strerror(errno));
                    break;
                default:
                    // 事件就绪
                    logMessage(NORMAL, "have event ready"); // epoll模型ET模式下，事件就绪只会通知一次，默认LT
                    handlerEvent(n);
                    break;
                }
            }
        }
        void handlerEvent(int readyNum)
        {
            // 无需遍历额外数组，_revents有readyNum个关心事件就绪的fd
            for (int i = 0; i < readyNum; ++i)
            {
                int sock = _revents[i].data.fd;
                uint32_t events = _revents[i].events;
                if (sock == _listensock && (events & EPOLLIN))
                {
                    Accepter();
                }
                else if (events & EPOLLIN)
                {
                    Reader(i);
                }
            }
        }
        void Accepter()
        {
            std::string clientip;
            uint16_t clientport = -1;
            int sock = Sock::Accept(_listensock, &clientip, &clientport);
            if (sock < 0)
            {
                logMessage(ERROR, "accept error: %s", strerror(errno));
                return;
            }
            struct epoll_event ev;
            ev.data.fd = sock;
            ev.events = EPOLLIN;
            epoll_ctl(_epollfd, EPOLL_CTL_ADD, sock, &ev);
        }
        void Reader(int pos)
        {
            // 直接读不能保证读到一个完整报文
            char buffer[1024];
            int fd = _revents[pos].data.fd;
            ssize_t s = recv(fd, buffer, sizeof(buffer) - 1, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                logMessage(NORMAL, "client #: %s", buffer);
                std::string response = _func(buffer);
                response += '\n';
                send(fd, response.c_str(), response.size(), 0);
            }
            else if (s == 0)
            {
                // 建议先从epoll删除，再关闭
                epoll_ctl(_epollfd, EPOLL_CTL_DEL, fd, nullptr);
                close(fd);
                logMessage(NORMAL, "client quit");
            }
            else
            {
                epoll_ctl(_epollfd, EPOLL_CTL_DEL, fd, nullptr);
                close(fd);
                logMessage(ERROR, "read error : %d %s", errno, strerror(errno));
            }
        }

        ~EpollServer()
        {
            if (_listensock != defaultfd)
                close(_listensock);
            if (_epollfd != defaultfd)
                close(_epollfd);
            if (_revents)
                delete[] _revents;
        }
    };
}